<?php
class UserAdminFormatter implements Formatter {
    private $data;

    function __construct($result) {
        $this->data = $result;
    }
    
    function generateResult() {
        $result = array();
        for ($i = 0; $i < count($this->data); $i++) {
            $result[] = array(
                id => $this->data[$i]['user_id'],
                cell => array(
                    $this->data[$i]['username'] ,
                    $this->data[$i]['title'] . " " . $this->data[$i]['firstname'] . " " . $this->data[$i]['lastname'],
                    $this->data[$i]['email'],
                    $this->data[$i]['role'] == "2",
                    $this->data[$i]['role'] != "0",
                    $this->data[$i]['registered'],
                ),
            );
        }
        return $result;
    }
}

class UserModel extends BaseModel implements Model {
    function __construct() {
        parent::__construct("users", "user_id");
        $this->addField("user_id", Model::TYPE_INT, Model::MOD_PRIMARY);
        $this->addField("username", Model::TYPE_INT);
        $this->addField("password", Model::TYPE_INT);
        $this->addField("wantnewsletter", Model::TYPE_INT);
        $this->addField("email", Model::TYPE_VARCHAR);
        $this->addField("firstname", Model::TYPE_VARCHAR);
        $this->addField("lastname", Model::TYPE_VARCHAR);
        $this->addField("title", Model::TYPE_VARCHAR);
        $this->addField("ticket", Model::TYPE_VARCHAR);
        $this->addField("role", Model::TYPE_INT);
        $this->addField("company_profile_id", Model::TYPE_INT);
        $this->addField("registered", Model::TYPE_DATE);
        $this->addField("registertype", Model::TYPE_INT);
        $this->addField("profileupdated", Model::TYPE_INT);
        $this->addField("bulkcreated", Model::TYPE_INT);
        $this->addField("decryptedpw", Model::TYPE_VARCHAR);
    }

    public function setWantNewsletter($id) {
        $query = QueryHelper::update("users", array(
            wantnewsletter => 1,
        ), "user_id=$id");
        Database::executeQuery($query);
    }

    public function clearWantNewsletter($id) {
        $query = QueryHelper::update("users", array(
            wantnewsletter => 0,
        ), "user_id=$id");
        Database::executeQuery($query);
    }

    public function renderAlias($record) {
        $result = $record;
        $result['name'] = $result['firstname'] . " " . $result['lastname'];
        return $result;
    }

    public function setProfileUpdated($id) {
        $query = QueryHelper::update("users", array(profileupdated => 1), "user_id=$id");
        Database::executeQuery($query);
    }

    public function getBulkUsers($page, $reccount, $usertype = "") {
        $start = ($page-1) * $reccount;
        $extracondition = "";
        if ($usertype != "") {
            $extracondition = " AND registertype=$usertype";
        }
        $query = "SELECT user_id, firstname, lastname, email, companyname FROM users ".
                 "JOIN companies ON companies.company_id=users.company_profile_id ".
                 "WHERE bulkcreated=1 ".
                 $extracondition . " "
        ;
        $res = Database::executeQuery($query);
        return Database::getDatafromResource($res);
    }

    public function getBulkUserCount() {
        $query = "SELECT count(*) AS c FROM users WHERE bulkcreated=1";
        $res = Database::executeQuery($query);
        return Database::getSimpleField($res);
    }

    public function unsubscribeEmail($email) {
        $query = "UPDATE users set wantnewsletter=0 where email='$email'";
        Database::executeQuery($query);
    }

    public function getUsersForemailsending($count, $type) {
        $extracondition = "";
        if ($type != "") {
            $extracondition .= " AND registertype=$type ";
        }
        $query = "SELECT * FROM users ".
                 "JOIN companies ON companies.company_id=users.company_profile_id ".
                 "WHERE bulkcreated=1 ". $extracondition . " ".
                 "LIMIT 0, $count"
        ;
        $res = Database::executeQuery($query);
        $result = Database::getDataFromResource($res);
        $idlist = array();
        for ($i = 0; $i < count($result); $i++) {
            $idlist[] = $result[$i]['user_id'];
        }
        $query = "UPDATE users SET bulkcreated=0 WHERE user_id IN (" . implode(",", $idlist) . ")";
        Database::executeQuery($query);
        return $result;
    }

    public function evaluate($ticket) {
        $result = false;
        $res = Database::executeQuery("UPDATE users SET ticket='', role=1, registered=now() WHERE ticket='$ticket'");
        if (mysql_affected_rows() > 0) { $result = true; }
        return $result;
    }

    public function setInvoiceUser($userid, $username) {
        $query = "UPDATE users SET eszamla_username='$username' WHERE user_id=$userid";
        Database::executeQuery($query);
    }

    public function getVisitors() {
        $query = "SELECT username AS companyname, user_id AS company_id, email AS email1 FROM suers WHERE registertype = 6";
        $res = Database::executeQuery($query);
        return Database::getDataFromResource($res);
    }

    public function setAdmin($userid) {
        $query = "UPDATE users SET role=2 WHERE user_id=$userid";
        Database::executeQuery($query);
    }
    
    public function clearAdmin($userid) {
        $query = "UPDATE users SET role=1 WHERE user_id=$userid";
        Database::executeQuery($query);
    }

    public function activateUser($userId) {
        $query = "UPDATE users SET role=1 WHERE user_id=$userId";
        Database::executeQuery($query);
    }

    public function deactivateUser($userId) {
        $query = "UPDATE users SET role=0 WHERE user_id=$userId";
        Database::executeQuery($query);
    }

    public function setCompanyProfileId($profileId) {
        $query = "UPDATE users SET company_profile_id=$profileId WHERE user_id=". $_SESSION['userdata']['user_id'];
        Database::executeQuery($query);
    }

    public function userExists($username) {
        $res = Database::executeQuery("SELECT count(*) AS c FROM users WHERE username='$username'");
        $result = Database::getDataFromResource($res);
        if ($result[0]['c'] > 0) { return true; }
        return false;
    }

    public function checkUserLogin($username, $password, $ticket='') {
        $pw = md5($password);
        $res = Database::executeQuery("SELECT count(*) AS c FROM users WHERE username='$username' AND password='$pw' AND (ticket IS NULL OR ticket='$ticket')");
        $result = Database::getDataFromResource($res);
        if ($result[0]['c'] > 0) { 
			$res = Database::executeQuery("UPDATE users SET ticket='' WHERE username='$username'");
			return true; 
		}
        return false;
    }

    public function getUserData($username) {
        $res = Database::executeQuery("SELECT * FROM users WHERE username='$username'");
        $result = Database::getDataFromResource($res);
        return $result[0];
    }

    public function setUserCompanyProfile($userId, $cpId) {
        $query = "UPDATE user SET company_profile_id=$cpId WHERE user_id=$userId";
        Database::executeQuery($query);
    }

    public function isAuthorized($operation, $subject = "") {
        return true;
//        if (Auth::isAdmin()) { return true; }
/*
        switch ($operation) {
            case "update" :
            case "delete" :
            case "addnew" : {
                if (Auth::canChangeDrivers()) { return true; }
            }
            case "list" : {
                if (Auth::canListDrivers()) { return true; }
            }
        }
        return false;
*/
    }

    public function modifyDatabaseInput($data) {
        $result = array();
        foreach ($data as $key=>$value) {
            if ($key == "password2") { continue; }
            if ($key == "random") { continue; }
            if ($key == "captcha") { continue; }
            else if ($key == "password") { $result['password'] = md5($value); }
            else { $result[$key] = $value; }
        }
        return $result;
    }
	
}

?>
